package com.xcc.httpUtils.request;

import com.xcc.httpUtils.builder.PostFormBuilder;
import com.xcc.httpUtils.callback.IUplodingCallback;
import okhttp3.*;

import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by zhy on 15/12/14.
 */
public class PostFormRequest extends BaseHttpRequest {

    private List<PostFormBuilder.FileInput> files;
    private IUplodingCallback mIUplodingCallback;

    /**
     * @param url url
     * @param tag 标记
     * @param params 参数
     * @param headers headers
     * @param files 文件列表
     * @param iUplodingCallback 上传回调
     */
    public PostFormRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, String json, List<PostFormBuilder.FileInput> files, IUplodingCallback iUplodingCallback) {
        super(url, tag, params, headers, json);
        this.files = files;
        if(iUplodingCallback != null){
            this.mIUplodingCallback = iUplodingCallback;
        }
    }


    @Override
    protected RequestBody buildRequestBody() {
        if (files == null || files.isEmpty()) {
            FormBody.Builder builder = new FormBody.Builder();
            addParams(builder);
            FormBody formBody = builder.build();
            return formBody;
        } else {
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
            addParams(builder);

            for (int i = 0; i < files.size(); i++) {
                PostFormBuilder.FileInput fileInput = files.get(i);
                RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file);
                builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody);
            }
            return builder.build();
        }
    }

    @Override
    protected Request buildRequest(RequestBody requestBody) {
        CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener() {
            @Override
            public void onRequestProgress(final long bytesWritten, final long contentLength) {
                if(mIUplodingCallback != null){
                    mIUplodingCallback.inProgress(bytesWritten * 1.0f / contentLength, contentLength);
                }
            }
        });
        return builder.post(countingRequestBody).build();
    }

    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = null;
        try {
            contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    private void addParams(MultipartBody.Builder builder) {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                        RequestBody.create(null, params.get(key)));
            }
        }
    }

    private void addParams(FormBody.Builder builder) {
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
    }

}
